package com.yyt.bean_copy_demo.service;

import com.yyt.bean_copy_demo.model.UserSource;
import com.yyt.bean_copy_demo.model.UserTarget;
import org.springframework.beans.BeanUtils;
import org.springframework.cglib.beans.BeanCopier;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * @author yeyangtao created at 2021/4/9 15:55
 */
public class UserService {
    private final static Integer MAX = 10000;

    public static void main(String[] args) {
        List<UserSource> userSourceList = init(MAX);

        List<UserTarget> userTargetList = new ArrayList<>(4 * MAX);
        long start3 = System.currentTimeMillis();
        userSourceList.forEach(u -> {
            UserTarget userTarget = new UserTarget();
            try {
                org.apache.commons.beanutils.BeanUtils.copyProperties(userTarget, u);
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
            userTargetList.add(userTarget);
        });
        System.err.println("apache工具类耗时:" + (System.currentTimeMillis() - start3));

        long start1 = System.currentTimeMillis();
        userSourceList.forEach(u -> {
            UserTarget userTarget = new UserTarget();
            BeanUtils.copyProperties(u, userTarget);
            userTargetList.add(userTarget);
        });
        System.err.println("Spring工具类耗时:" + (System.currentTimeMillis() - start1));

        long start2 = System.currentTimeMillis();
        userSourceList.forEach(u -> {
            UserTarget userTarget = u.convert();
            userTargetList.add(userTarget);
        });
        System.err.println("Set方法耗时:" + (System.currentTimeMillis() - start2));

        long start4 = System.currentTimeMillis();
        userSourceList.forEach(u -> {
            UserTarget userTarget = new UserTarget();
            BeanCopier beanCopier = BeanCopier.create(u.getClass(), UserTarget.class, false);
            beanCopier.copy(u, userTarget, null);
            userTargetList.add(userTarget);
        });
        System.err.println("Cglib BeanCopier工具类耗时:" + (System.currentTimeMillis() - start4));

        System.err.println(userTargetList.size());
    }

    public static List<UserSource> init(int max) {
        return new Random().ints(0, Integer.MAX_VALUE)
                .distinct()
                .limit(max)
                .boxed()
                .map(UserSource::new)
                .collect(Collectors.toList());
    }
}
